import { spawn } from 'child_process'
import nodePath from 'path'
const oxlintPlugin = (options = {}) => {
  let timeoutId = null
  const { params = [], path = '' } = options
  const debounceTime = 300
  const executeCommand = (command = ['oxlint', ...params]) => {
    return new Promise((resolve, reject) => {
      const cwd = nodePath.join(process.cwd(), path)
      const child = spawn('npx', command, { stdio: 'inherit', cwd, env: process.env })
      child.on('close', (code) => {
        resolve()
        console.log('oxLint检测-命令：', command.join(' '))
        console.log(`oxLint检测-检测完成-子进程退出码：${code}`)
      })
      child.on('error', (err) => {
        reject(err)
        console.error(`oxLint检测-子进程启动失败: ${err.message}`)
      })
    })
  }
  const handleCommandExecution = async () => {
    if (timeoutId) {
      clearTimeout(timeoutId)
    }
    timeoutId = setTimeout(async () => {
      try {
        await executeCommand()
      } catch (error) {
        console.error('oxLint检测-失败', error)
      }
    }, debounceTime)
  }
  return {
    name: 'vite-plugin-oxlint',
    async buildStart () {
      await handleCommandExecution()
    },
    async handleHotUpdate () {
      await handleCommandExecution()
    },
  }
}
export default oxlintPlugin
